package top.infopub.mgr.bpa.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.dto.bpa.BpaPublicProInfoDto;
import top.infopub.dto.bpa.MicroExamDto;
import top.infopub.dto.bpa.MicroExamQueryDto;
import top.infopub.dto.bpa.MicroExamTaxDto;
import top.infopub.enums.bpa.BpaProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.bpa.dao.MicroExamDao;
import top.infopub.mgr.bpa.dao.MicroExamTaxMapper;
import top.infopub.mgr.bpa.jsonVo.MicroExamDetailJsonVo;
import top.infopub.mgr.bpa.service.BpaProcessManageService;
import top.infopub.mgr.bpa.service.MicroExamService;
import top.infopub.mgr.bpa.vo.MicroExamPo;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.mgr.mkt.service.ProjectInfoService;
import top.infopub.mgr.mkt.service.SetupProService;
import top.infopub.mgr.util.FileAttrUtils;
import top.infopub.model.bpa.MicroExam;
import top.infopub.model.bpa.MicroExamTax;
import top.infopub.model.bpa.MicroExamTaxExample;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MicroExamServiceImpl extends GenericServiceImpl<MicroExam, String> implements
        MicroExamService {

    @Autowired
    private MicroExamDao microExamDao;
    @Resource
    private MicroExamTaxMapper microExamTaxMapper;
    @Autowired
    private SetupProService setupProService;
    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;
    @Autowired
    private OAFlowService oaFlowService;
    @Autowired
    private BpaProcessManageService bpaProcessManageService;
    @Autowired
    private ProjectInfoService projectInfoService;

    @Override
    public GenericDao<MicroExam, String> getDao() {
        return microExamDao;
    }

    @Override
    public Page<MicroExamPo> selectByDomainWhere(Page<MicroExamPo> page, MicroExamQueryDto microExamQueryDto) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<MicroExamPo>) microExamDao.selectByDomainWhere(microExamQueryDto);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RspVo save(MicroExamDetailJsonVo jsonVo, Integer submitType) {
        MicroExamDto microExamDto = jsonVo.getInfo();
        MicroExam microExam = new MicroExam();
        //数据拷贝
        BeanUtils.copyProperties(microExamDto, microExam);
        microExam.setUptBy(SessionUserUtils.getSessionUserId());
        microExam.setUptTime(new Date());
        if (StringUtils.isNotBlank(microExam.getId())) {
            //校验数据是否存在
            MicroExam tmpMe = microExamDao.selectByPrimaryKey(microExam.getId());
            if (tmpMe == null) return RspVo.getFailureResponse(400, "小微评审数据不存在");
            //判断审批状态
            if (StringUtils.isNotBlank(tmpMe.getProcessStatus())
                    && (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), tmpMe.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), tmpMe.getProcessStatus()))) {
                return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
            }
            microExamDao.updateByIdSelective(microExam);
            microExam.setOaId(tmpMe.getOaId());
        } else {
            microExam.setAddBy(SessionUserUtils.getSessionUserId());
            microExam.setAddTime(new Date());
            microExam.setCodes(IdFactory.getUUIDUpper());
            microExamDao.insertSelective(microExam);
        }

        /**2、子表 小微评审-纳税人员入库 **/
        List<MicroExamTaxDto> microExamTaxDto = jsonVo.getMicroExamTaxDtos();
        MicroExamTax microExamTax = new MicroExamTax();
        List<MicroExamTax> microExamTaxs = new ArrayList<>();
        //数据拷贝
        for (MicroExamTaxDto o : microExamTaxDto) {
            BeanUtils.copyProperties(o, microExamTax);
            microExamTax.setParentId(microExam.getId());
            microExamTax.setUptBy(SessionUserUtils.getSessionUserId());
            microExamTax.setUptTime(new Date());
            microExamTax.setId(IdFactory.getUUIDUpper());
            microExamTax.setAddBy(SessionUserUtils.getSessionUserId());
            microExamTax.setAddTime(new Date());
            microExamTaxs.add(microExamTax);
        }
        MicroExamTaxExample example = new MicroExamTaxExample();
        example.or().andParentIdEqualTo(microExam.getId());
        //子表先删除后插入
        microExamTaxMapper.deleteByExample(example);
        microExamTaxMapper.insertBatch(microExamTaxs);
        /** 3、更新附件表-MKT_PROJECT_ATTACHMENT **/
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if (jsonVo.getFileAtt() != null) {
            String[] fileAtt = jsonVo.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = FileAttrUtils.createProjectFileAtta(microExamDto.getId(), file);
                attachmentList.add(attachment);
            }
        }

        projectAttachmentDao.deleteByWhere(microExamDto.getId(), ProjectFileTypeEnum.FILE_TYPE143.getCode(), null);
        if (attachmentList != null && attachmentList.size() > 0) {
            projectAttachmentDao.insertBatch(attachmentList);
        }
        /** 5、如果是提交  则进行流程***/
        if (1 == submitType) {
            if (StringUtils.isNotBlank(microExam.getOaId())) {
                oaFlowService.finishOA(microExam.getOaId());
            }
            MicroExamDetailJsonVo detail = getDetail(microExam.getId());
            String json = JSON.toJSONString(detail);
            AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
            bpaProcessManageService.sendProcess(BpaProcessDetailTypeEnum.PRO_NODE_TYPE28, json, microExam.getId(), microExam.getProCode(), vo);
        }
        return RspVo.getSuccessResponse();
    }

    @Override
    public MicroExamDetailJsonVo getDetail(String id) {
        //判断id是否为空 如果为空则表示是新增 不为空表示是详情页面
        MicroExamDetailJsonVo microExamDetailJsonVo = new MicroExamDetailJsonVo();
        if (StringUtils.isBlank(id)) {
            microExamDetailJsonVo = addDetailReturnData(microExamDetailJsonVo);
        } else {
            microExamDetailJsonVo = detailReturnData(id, microExamDetailJsonVo);
        }
        return microExamDetailJsonVo;
    }

    @Override
    public MicroExamPo queryById(String id) {
        return microExamDao.queryById(id);
    }

    //新增的数据封装返回
    public MicroExamDetailJsonVo addDetailReturnData(MicroExamDetailJsonVo microExamDetailJsonVo) {
        //返回所有的项目code和name
        microExamDetailJsonVo.setProInfoList(setupProService.queryPublicProInfo());
        return microExamDetailJsonVo;
    }

    //查看详情的数据返回
    public MicroExamDetailJsonVo detailReturnData(String id, MicroExamDetailJsonVo microExamDetailJsonVo) {

        //小微评审基础信息
        MicroExamPo bizPlanDetailDto = microExamDao.queryById(id);
        MicroExamDto microExamDto = new MicroExamDto();
        BeanUtils.copyProperties(bizPlanDetailDto, microExamDto);
        //项目合同基本信息
        BpaPublicProInfoDto dto = projectInfoService.queryBpaProInfoByProCode(bizPlanDetailDto.getProCode());
        BeanUtils.copyProperties(dto, microExamDto);
        /** 1、主表基础信息 **/
        microExamDetailJsonVo.setInfo(microExamDto);
        /****子表-纳税人员信息 **/
        MicroExamTaxExample example = new MicroExamTaxExample();
        example.setOrderByClause("ADD_TIME DESC ");
        example.or().andParentIdEqualTo(microExamDto.getId());

        List<MicroExamTax> microExamTax = microExamTaxMapper.selectByExample(example);
        List<MicroExamTaxDto> microExamTaxDtos = new ArrayList<>();
            for (MicroExamTax examTax : microExamTax) {
                MicroExamTaxDto microExamTaxDto=new MicroExamTaxDto();
                    microExamTaxDto.setId(examTax.getId());
                    microExamTaxDto.setTaxUserName(examTax.getTaxUserName());
                    microExamTaxDto.setAmountPayable(examTax.getAmountPayable());
                    microExamTaxDto.setActualAmount(examTax.getActualAmount());
                    microExamTaxDto.setParentId(examTax.getParentId());
                    microExamTaxDtos.add(microExamTaxDto);
            /** 2、子表 纳税人员信息 **/
            microExamDetailJsonVo.setMicroExamTaxDtos(microExamTaxDtos);
        }

        /** 3、项目信息  **/
//        microExamDetailJsonVo.setProNameAndId(listMap);

        //附件信息表
        List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(id, ProjectFileTypeEnum.FILE_TYPE142.getCode(), null);
        /**4、附件信息 **/
        microExamDetailJsonVo.setFileAtt(setupProService.fileAttaListToArray(projectAttaList));

        return microExamDetailJsonVo;
    }

}